package com.bizframework.security.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.bizframework.security.convertor.PermissionTreeDTOConvertor;
import com.bizframework.security.domain.dao.PermissionDao;
import com.bizframework.security.domain.dao.UserDao;
import com.bizframework.security.domain.entity.Permission;
import com.bizframework.security.dto.PermissionTreeDTO;
import com.bizframework.security.service.PermissionService;

public class PermissionServiceImpl implements PermissionService {

	private UserDao userDao;

	private PermissionDao permissionDao;

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public void setPermissionDao(PermissionDao permissionDao) {
		this.permissionDao = permissionDao;
	}

	public List<PermissionTreeDTO> getPermissionTree() throws Exception {
		List<Permission> permissions = permissionDao.getAllPermissionByOrder();

		HashMap<String, PermissionTreeDTO> map = new HashMap<String, PermissionTreeDTO>();

		List<PermissionTreeDTO> result = new ArrayList<PermissionTreeDTO>();
		
		List<PermissionTreeDTO> temp = new ArrayList<PermissionTreeDTO>();
		for (Permission permission : permissions) {
			PermissionTreeDTO treeNode = PermissionTreeDTOConvertor
					.entityToTreeDTO(new PermissionTreeDTO(), permission);
			map.put(permission.getId(), treeNode);
			temp.add(treeNode);
			if (permission.getParentPermission() == null) {
				result.add(treeNode);
			}
		}

		for (PermissionTreeDTO treeItem : temp) {
			if (map.containsKey(treeItem.getParentId())) {
				map.get(treeItem.getParentId()).getChildren().add(treeItem);
			}
		}
		return result;
	}

	public List<String> getUserPermissionCodes(String userName)
			throws Exception {
		return userDao.getUserPermissionCodes(userName);
	}
}